package cn.liip.demo.config;

import javax.sql.DataSource;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;

@Configuration
public class DruidConfiguration {
	//private static final Logger logger = LoggerFactory.getLogger(DruidConfiguration.class);

	//private static final String DB_PREFIX = "spring.datasource";
	
	public DataSource dataSource() {
		DruidDataSource datasource = new DruidDataSource();
		return datasource;
	}
	
	@Bean//手动初始化DruidDataSource对象
	public ServletRegistrationBean druidServlet() {
		ServletRegistrationBean reg = new ServletRegistrationBean();
		reg.setServlet(new StatViewServlet());
		reg.addUrlMappings("/monitor/druid/*");
		/** 白名单 */
		reg.addInitParameter("allow", "127.0.0.1");
		/** IP黑名单(共同存在时，deny优先于allow) */
		reg.addInitParameter("deny", "192.168.2.105");
		/** /druid/login.html登录时账号密码 */
		reg.addInitParameter("loginUsername", "root");
		reg.addInitParameter("loginPassword", "root");
		/** 是否能够重置数据 禁用HTML页面上的“Reset All”功能 */
		reg.addInitParameter("resetEnable", "false");
		return reg;
	}
	
	/**
	     * 注册一个：filterRegistrationBean 相当于在web.xml中声明了一个Filter
	     */
	@Bean
	public FilterRegistrationBean druidStatFilter() {
	        FilterRegistrationBean druidStatFilter = new FilterRegistrationBean();
	        druidStatFilter.setFilter(new WebStatFilter());
	        /** 添加过滤规则. */
	        druidStatFilter.addUrlPatterns("/*");
	        /** 监控选项滤器 */
	        druidStatFilter.addInitParameter("DruidWebStatFilter", "/*");
	        /** 添加不需要忽略的格式信息. */
	        druidStatFilter.addInitParameter("exclusions",
	                "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/monitor/druid/*");
	        /** 配置profileEnable能够监控单个url调用的sql列表 */
	        druidStatFilter.addInitParameter("profileEnable", "true");
	        /** 当前的cookie的用户 */
	        druidStatFilter.addInitParameter("principalCookieName", "USER_COOKIE");
	        /** 当前的session的用户 */
	        druidStatFilter
	                .addInitParameter("principalSessionName", "USER_SESSION");
	        return druidStatFilter;
	    }
}
